<?php

/**
 * 后台文章栏目管理
 * @author  xiaobai
 * @date    2017-01-12
 */

namespace app\panel\controller;

use app\common\controller\Panelbase;
use app\common\model\Column as column_model;
use util\Columntree;

class Column extends Panelbase
{
    public function initialize()
    {
        parent::initialize();
        $this->model = new column_model();

        $this->assign('types', column_model::$types);
    }

    public function index()
    {
        $list = $this->model->selectColumn();
        
        $this->assign("list", $list);
        return $this->fetch();
    }

    public function add()
    {
        $parentid = input('param.parentid', 0, 'intval');
        $columns  = $this->model->selectColumn();

        //模板文件地址
        $template = get_theme_style();

        $this->assign('columns', $columns);
        $this->assign('template', $template);
        $this->assign('parentid', $parentid);
        return $this->fetch();
    }

    public function add_post()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $data['setting'] = json_encode($data['setting']);
            $data['content'] = '';

            // 数据验证
            $result = $this->validate($data,'column');
            if (true !== $result) {
                $this->error($result);
            }

            if ($this->model->save($data)) {
                $this->success('保存成功', Url('index'));
            } else {
                $this->error($this->model->getError());
            }
        } else {
            $this->error('请求错误');
        }
    }

    public function edit()
    {
        $id = input("param.id");
        $column = $this->model->where('id',$id)->find()->toArray();
        if (empty($column)) {
            $this->error('数据不存在');
        }
        $column['setting'] = json_decode($column['setting'], true);

        $columns = $this->model->selectColumn();
        //模板文件地址
        $template = get_theme_style();

        $this->assign('template', $template);
        $this->assign('columns', $columns);
        $this->assign($column);
        return $this->fetch();
    }

    public function edit_post()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $data['setting'] = json_encode($data['setting']);

            // 数据验证
            $result = $this->validate($data,'column');
            if (true !== $result) {
                $this->error($result);
            }

            if ($this->model->isUpdate(true)->save($data)) {
                $this->success('保存成功', Url('index'));
            } else {
                $this->error($this->model->getError());
            }
        } else {
            $this->error('请求错误');
        }
    }
}
